import React, { useEffect, useState, useRef } from 'react'
import './App.css'
const listData = new Array(1000).fill(0).map((item, index) => {
  return {
    id: index,
    value: index
  }
})
export default function () {
  const [startOffset, setStartOffset] = useState(0)
  const [startIndex, setStartIndex] = useState(0)
  const [endIndex, setEndIndex] = useState(0)
  useEffect(() => {
    setEndIndex(startIndex + visihleCount)
  }, [startIndex])
  //总列表高度
  const listHeight = listData.length * 50
  //可以展示的列表项数
  const visihleCount = Math.ceil(500 / 50)
  //上方的偏移量对应的style
  const getTransform = {
    transform: `translateY(${startOffset}px)`
  }
  const listRef = useRef(null)
  const scrollEvent = (e) => {
    const scrollTop = listRef.current.scrollTop//内部结构在上一级上滚动了多少距离
    setStartOffset(scrollTop-(scrollTop%50))
    setStartIndex(Math.floor(scrollTop / 50))
  }
  const visibleData = listData.slice(startIndex, Math.min(endIndex,listData.length))
  return (
    <div className='container' onScroll={scrollEvent} ref={listRef}>
      <div className="list-phantom" style={{height:`${listHeight}px`}}></div>
      <div className="list" style={getTransform}>
        <ul>
          {
            visibleData.map(item => {
              return <li key={item.id}>{item.value}</li>
            })
          }
        </ul>
      </div>
    </div>
  )
}
